﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>选项联动控件</title>
    <script type="text/javascript" src="../../../Scripts/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="../../../Scripts/QueryString.js"></script>
    <link href="../../../../DataUser/Style/ccbpm.css" rel="stylesheet" />
    <script src="../../../Scripts/config.js" type="text/javascript"></script>
    <script src="../../../Comm/Gener.js" type="text/javascript"></script>
    <script src="../../../Scripts/layui/layui/layui.js"></script>
    <link href="../../../Scripts/layui/layui/css/layui.css" rel="stylesheet" />
    <script src="../../../Scripts/layui/layui/lay/modules/laytpl.js"></script>
    <script type="text/javascript">
        //页面启动函数.
        var initData = {};
        var pageData = {};
        var radioValue = -1;//当前选定的列表值，number类型
        var IsEnableJS = "0";//是否启用 ，string类型
        var Sys_MapAttr = [];
        var FrmAttachments = [];//附件
        var MapDtls = [];//从表
        var Sys_FrmRB = [];//不同列表值的配置
        var AttrTableData;
        var DtlTableData;
        var AthTableData;
        var attrTable;
        let currentSaveRb = [];//要配置的选项
        var expStrs = "AtPara,FID,OID,Title,MyNum,FK_NY,Emps,RDT,EDT,CDT,Rec,";
        layui.use(['element', 'table', 'form', 'laydate', 'layer'], function () {
            var layer = layui.layer;
            var laydate = layui.laydate;
            var AttrTable = layui.table;
            var DtlTable = layui.table;
            var AthTable = layui.table;
            var form = layui.form;
            $(function () {
                InitPage();
            });
            async function InitPage() {
                const loading = await asyncLoad('正在加载，请稍后...');
                try {
                    pageData = {
                        FK_MapData: GetQueryString("FK_MapData"),
                        KeyOfEn: GetQueryString("KeyOfEn"),
                        SelectIntKey: GetQueryString("SelectIntKey"),
                        MyPK: GetQueryString("MyPK")
                    };
                    if (pageData.selectIntKey == null)
                        pageData.selectIntKey = "0";
                    //设置是否启用?
                    var pkval = GetQueryString("FK_MapData") + "_" + GetQueryString("KeyOfEn");
                    var attr = new Entity("BP.Sys.MapAttr", pkval);
                    if (attr.AtPara.indexOf('@IsEnableJS=1') >= 0) {
                        IsEnableJS = "1";
                    }

                    //获得的数据.
                    var handler = new HttpHandler("BP.WF.HttpHandler.WF_Admin_FoolFormDesigner_MapExt");
                    handler.AddUrlData();
                    var data = handler.DoMethodReturnString("RadioBtns_Init");

                    if (data != undefined && data.indexOf('err@') == 0) {
                        console.error(data);
                        return;
                    }

                    initData = JSON.parse(data);
                    Sys_MapAttr = initData['Sys_MapAttr'];//字段集合
                    FrmAttachments = initData['FrmAttachments'];//附件集合
                    MapDtls = initData['MapDtls'];//从表集合
                    Sys_FrmRB = initData['Sys_FrmRB'];//列表配置
                    renderRadioList();//渲染列表值单选框
                    rederIsEnableJS();//渲染启用禁用下拉框
                    Reload();
                    form.render(); //更新全部
                    setTimeout(() => {
                        layer.close(loading);
                    }, 1000);

                } catch (e) {
                    layer.msg('获取数据失败' + e, { icon: 2 });
                    layer.close(loading);
                }

            }
            //刷新表单
            function Reload() {
                if (IsEnableJS === "1") {
                    $("#tabBox").show();
                    $("#listValue").show();
                } else {
                    $("#tabBox").hide();
                    $("#listValue").hide();
                }
                setData();
                renderTable();
            }
            //渲染是否启用下拉框
            function rederIsEnableJS() {
                var html = "";
                html += '<select id="IsEnableJS" name="IsEnableJS" lay-filter="IsEnableJS">';
                html += '<option value="1" ' + `${IsEnableJS === "1" ? "selected" : ""}` + '>启用</option>';
                html += '<option value="0" ' + `${IsEnableJS === "0" ? "selected" : ""}` + ' >禁用</option>';
                html += '</select>';
                $("#selectIsEnableJS").html(html);
            };
            //监听是否启用
            form.on('select(IsEnableJS)', function (data) {
                IsEnableJS = data.value;
                Reload();

            });
            //渲染列表值单选框
            function renderRadioList() {
                var html = "";
                initData.Sys_FrmRB.forEach((item, index) => {
                    var checked = "";
                    if (index === 0) {//首先展示第一个选项的各种值
                        checked = "checked";
                        radioValue = item.IntKey;
                    };
                    html += '<input type="radio" name="radio" value="' + item.IntKey + '" title="' + item.Lab + '" ' + checked + ' lay-filter="radioList"/>';
                });
                $("#radioList").html(html);
            };
            //监听列表值单选框，更新当前选中的列表值
            form.on('radio(radioList)', function (data) {
                //changeSys_FrmRB();//保存当前打开的列表配置
                radioValue = data.value;//更改当前选中的列表值
                Reload();
            });
            //根据列表值构造表格数据和配置数据
            function setData() {
                AttrTableData = [];
                DtlTableData = [];
                AthTableData = [];
                var sys_frmRB = Sys_FrmRB.filter((item) => item.IntKey === radioValue)[0];

                if (sys_frmRB.FieldsCfg == null) {
                    sys_frmRB.FieldsCfg = "";

                }
                if (sys_frmRB.SetVal == null) {
                    sys_frmRB.SetVal = "";
                }
                if (sys_frmRB.Tip == null) {
                    sys_frmRB.Tip = "";
                }
                if (sys_frmRB.Script == null) {
                    sys_frmRB.Script = "";
                }


                var fieldsCfg = sys_frmRB.FieldsCfg.split('@');//数据格式：["xxx=0","xxx=1"],值：0-4
                fieldsCfg.splice(0, 1);
                var setVal = sys_frmRB.SetVal.split('@');//数据格式：["xxx=123","xxx=李四"]
                Sys_MapAttr.forEach((item) => {
                    var thisRowData = {};
                    if (item.UIVisible == 1 && expStrs.indexOf(item.KeyOfEn) < 0) {
                        var thisFieldsCfg = fieldsCfg.filter((i) => i.indexOf(item.KeyOfEn) > -1)[0];
                        thisFieldsCfg = thisFieldsCfg ? thisFieldsCfg.split('=')[1] : "0";
                        var thisSetVal = setVal.filter((i) => i.indexOf(item.KeyOfEn) > -1)[0];
                        thisSetVal = thisSetVal ? thisSetVal.split('=')[1] : "";
                        thisRowData = {
                            title: item.Name,
                            id: item.KeyOfEn,
                            fieldsCfg: thisFieldsCfg,
                            setVal: thisSetVal,
                            UIBindKey: item.UIBindKey,
                            KeyOfEn: item.KeyOfEn,
                            MyDataType: item.MyDataType,
                            LGType: item.LGType,
                            UIContralType: item.UIContralType,
                        }
                        AttrTableData.push(thisRowData);
                    }
                });
                MapDtls.forEach((item) => {
                    var thisRowData = {};
                    var thisFieldsCfg = fieldsCfg.filter((i) => i.indexOf(item.No) > -1)[0];
                    thisFieldsCfg = thisFieldsCfg ? thisFieldsCfg.split('=')[1] : "0";
                    thisRowData = {
                        title: item.Name,
                        id: item.No,
                        fieldsCfg: thisFieldsCfg,
                        KeyOfEn: item.No
                    }
                    DtlTableData.push(thisRowData);
                });
                FrmAttachments.forEach((item) => {
                    var thisRowData = {};
                    var thisFieldsCfg = fieldsCfg.filter((i) => i.indexOf(item.MyPK) > -1)[0];
                    thisFieldsCfg = thisFieldsCfg ? thisFieldsCfg.split('=')[1] : "0";
                    thisRowData = {
                        title: item.Name,
                        id: item.MyPK,
                        fieldsCfg: thisFieldsCfg,
                        KeyOfEn: item.MyPK,
                    }
                    AthTableData.push(thisRowData);
                });
                $("#TB_Script").val(sys_frmRB.Script);
                $("#TB_Tip").val(sys_frmRB.Tip);
            }
            //渲染AttrTable属性值表格
            function renderTable() {
                attrTable = AttrTable.render({
                    elem: '#AttrTable'
                    , page: false
                    , height: 'full-200'
                    , limit: AttrTableData.length
                    , data: AttrTableData
                    , cols: [[ //表头
                        { type: 'numbers', fixed: 'left', }
                        , { field: 'title', title: '名称', align: 'center', width: 100 }
                        , { field: 'fieldsCfg', title: '设置', templet: '#radioFieldsCfg', align: 'center', width: 400, unresize: true }
                        , { field: 'setVal', title: '设置值', align: 'center', templet: '#setValue', unresize: true }
                    ]]
                    , done: function (res, curr, count) {
                        laydate.render({
                            elem: '#DateTime', //指定元素
                            type: 'datetime',
                        });
                        laydate.render({
                            elem: '#Date', //指定元素
                            type: 'date',
                        });
                    }
                });
                dtlTable = DtlTable.render({
                    elem: '#DtlTable'
                    , page: false
                    , height: 'full-200'
                    , limit: DtlTableData.length
                    , data: DtlTableData
                    , cols: [[ //表头
                        { type: 'numbers', fixed: 'left', }
                        , { field: 'title', title: '名称', align: 'center', width: 100, unresize: true }
                        , { field: 'fieldsCfg', title: '设置', templet: '#radioFieldsCfg', align: 'center', unresize: true }
                    ]]
                });
                athTable = AthTable.render({
                    elem: '#AthTable'
                    , page: false
                    , height: 'full-200'
                    , limit: AthTableData.length
                    , data: AthTableData
                    , cols: [[ //表头
                        { type: 'numbers', fixed: 'left', }
                        , { field: 'title', title: '名称', align: 'center', width: 100, unresize: true }
                        , { field: 'fieldsCfg', title: '设置', templet: '#radioFieldsCfg', align: 'center', unresize: true }
                    ]]
                });
            };
            form.on("select(setValue)", function (data) {
                var key = $(data.elem).attr("name").split("-")[1];
                AttrTableData = $.map(AttrTableData, function (item) {
                    if (item.KeyOfEn == key) {
                        return {
                            ...item,
                            setVal: data.value.toString(),
                        }
                    } else return item;
                });
            });
            form.on("radio(radioFieldsCfg)", function (data) {//改变设置
                var key = $(data.elem).attr("name").split("-")[1];
                AttrTableData = $.map(AttrTableData, function (item) {
                    if (item.KeyOfEn == key) {
                        return {
                            ...item,
                            fieldsCfg: data.value.toString(),
                        }
                    } else return item;
                });
                DtlTableData = $.map(DtlTableData, function (item) {
                    if (item.KeyOfEn == key) {
                        return {
                            ...item,
                            fieldsCfg: data.value.toString(),
                        }
                    } else return item;
                })
                AthTableData = $.map(AthTableData, function (item) {
                    if (item.KeyOfEn == key) {
                        return {
                            ...item,
                            fieldsCfg: data.value.toString(),
                        }
                    } else return item;
                })
            });

            //监听保存
            $("#save").click(function () {
                Save();
            });
            //执行保存
            async function Save() {
                const loading = await asyncLoad('正在保存...');
                try {
                    if (IsEnableJS == "0") {
                        SaveEnableJS("0");
                        Sys_FrmRB = $.map(Sys_FrmRB, function (item) {
                            return {
                                ...item,
                                FieldsCfg: '',
                                Script: '',
                                SetVal: '',
                                Tip: '',
                            };
                        });
                        var handler = new HttpHandler("BP.WF.HttpHandler.WF_Admin_FoolFormDesigner_MapExt");
                        handler.AddPara("data", JSON.stringify(Sys_FrmRB));
                        handler.AddPara("FK_MapData", pageData.FK_MapData);
                        handler.AddPara("FK_MapExt", pageData.MyPK);
                        handler.AddPara("KeyOfEn", pageData.KeyOfEn);
                        var data = handler.DoMethodReturnString("RadioBtns_Save");
                    } else {
                        //保存当前列表值
                        changeSys_FrmRB();
                        console.log("保存的数据:", Sys_FrmRB);
                        SaveEnableJS("1");
                        var handler = new HttpHandler("BP.WF.HttpHandler.WF_Admin_FoolFormDesigner_MapExt");
                        handler.AddPara("data", JSON.stringify(currentSaveRb));
                        handler.AddPara("FK_MapData", pageData.FK_MapData);
                        handler.AddPara("FK_MapExt", pageData.MyPK);
                        handler.AddPara("KeyOfEn", pageData.KeyOfEn);
                        var data = handler.DoMethodReturnString("RadioBtns_Save");
                    }
                } catch (e) {
                    layer.close(loading);
                    layer.msg('保存失败：' + e, { icon: 2 });
                    return;
                }
                setTimeout(() => {
                    layer.close(loading);
                }, 2000);
                layer.msg('保存成功', { icon: 1 });
                Reload();
            }

            var layer_Tip;
            //提示信息
            $("#AttrTableTips").on("mouseenter", function () {
                layer_Tip = layer.tips("注意:被联动的控件在经典表单模式下要占三行", '#AttrTableTips', {
                    tips: [1, "#"],  //1-4表示上右下左四个方向，# 可带背景色
                    area: ['auto', 'auto'], // 提示框宽高
                    time: 0  //自动关闭所需毫秒,0表示不自动关闭
                });
            });
            $("#AttrTableTips").on('mouseleave', function () { // 监听鼠标移出事件
                layer.close(layer_Tip);
            });

            //提示信息
            $("#SettingTips").on("mouseenter", function () {
                layer_Tip = layer.tips("需要为每个选择项设置显示与隐藏的内容，设置js, top的提示信息.", '#SettingTips', {
                    tips: [1, "#"],  //1-4表示上右下左四个方向，# 可带背景色
                    area: ['auto', 'auto'], // 提示框宽高
                    time: 0  //自动关闭所需毫秒,0表示不自动关闭
                });
            });
            $("#SettingTips").on('mouseleave', function () { // 监听鼠标移出事件
                layer.close(layer_Tip);
            });
        });


        //改变当前列表值的值
        function changeSys_FrmRB() {
            var fieldsCfg = '';
            var setVal = '';
            $.each(AttrTableData, function (index, item) {
                if (item.FieldsCfg == null && item.SetVal == null && item.Tip == null && item.Script == null) {
                    item.FieldsCfg = "";
                    item.SetVal = "";
                    item.Tip = "";
                    item.Script = "";
                }
                if (item.fieldsCfg != null && item.fieldsCfg != undefined && item.fieldsCfg != "" && item.fieldsCfg != "0") {
                    fieldsCfg += `@${item.KeyOfEn}=${item.fieldsCfg}`;
                };
                if (item.setVal != "" && item.setVal != null && item.setVal != undefined) {
                    setVal += `@${item.KeyOfEn}=${item.setVal}`;
                };
            });
            $.each(DtlTableData, function (index, item) {
                if (item.fieldsCfg != null && item.fieldsCfg != undefined && item.fieldsCfg != "" && item.fieldsCfg != "0") {
                    fieldsCfg += `@${item.KeyOfEn}=${item.fieldsCfg}`;
                };
                if (item.setVal != "" && item.setVal != null && item.setVal != undefined) {
                    setVal += `@${item.KeyOfEn}=${item.setVal}`;
                };
            });
            $.each(AthTableData, function (index, item) {
                if (item.fieldsCfg != null && item.fieldsCfg != undefined && item.fieldsCfg != "" && item.fieldsCfg != "0") {
                    fieldsCfg += `@${item.KeyOfEn}=${item.fieldsCfg}`;
                };
                if (item.setVal != "" && item.setVal != null && item.setVal != undefined) {
                    setVal += `@${item.KeyOfEn}=${item.setVal}`;
                };
            });
            var allValues = $("input[type='text']:not(.layui-input)");

            currentSaveRb = [];
            Sys_FrmRB.forEach((it) => {
                if (it.IntKey == radioValue) {
                    currentSaveRb.push(it);
                }
            });

            $.each(allValues, function (index, item) {
                var key = $(item).attr("name").split("_")[1];
                var value = $(item).val();
                if (value != "" && value != null && value != undefined) {
                    setVal += `@${key}=${value}`;
                }
            });

            currentSaveRb[0].FieldsCfg = fieldsCfg;
            currentSaveRb[0].SetVal = setVal;
            currentSaveRb[0].Script = $("#TB_Script").val();
            currentSaveRb[0].Tip = $("#TB_Tip").val();
        };


        //设置是否启用：value="0" "1"
        function SaveEnableJS(value) {
            var pkval = GetQueryString("FK_MapData") + "_" + GetQueryString("KeyOfEn");
            var attr = new Entity("BP.Sys.MapAttr", pkval);
            attr.SetPara("IsEnableJS", value);
            attr.Update();
        }

    </script>
</head>
<style>
    .IsEnableJS {
        float: left;
        display: block;
        padding: 9px 5px;
        width: 110px;
        font-weight: 400;
        line-height: 20px;
        text-align: right;
        font-size: 18px;
    }

    #turnOn .layui-form-select {
        width: 400px;
    }

    .layui-table-cell {
        overflow: visible;
    }

    td .layui-input.layui-unselect {
        height: 33px;
    }
</style>
<body>
    <form class="layui-form">
        <div class="layui-form-item">
            <div class="IsEnableJS">选项联动控件</div>
            <div style="display:flex;justify-content:flex-end" id="turnOn">
                <div id="selectIsEnableJS">

                </div>
                <button type="button" class="layui-btn" id="save">保存</button>
            </div>
        </div>
        <hr />
    </form>
    <form class="layui-form" id="listValue">
        <!--列表值单选框---start-->

        <div class="layui-form-item">
            <label class="layui-form-label">列表值</label>
            <div class="layui-input-block" id="radioList">
                列表值未渲染
            </div>
        </div>
    </form>
    <!--列表值单选框---end-->
    <!--Tab---start-->
    <div class="layui-tab layui-tab-brief" lay-filter="tab" id="tabBox">
        <ul class="layui-tab-title">
            <li class="layui-this" lay-id="Attr">属性值</li>
            <li lay-id="Dtl">从表</li>
            <li lay-id="Ath">附件</li>
            <li lay-id="Setting">高级设置</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show">
                <div style="margin-left: 10px">
                    联动其他的控件使其属性该表(可见，只读)
                    <i class="layui-icon" style="vertical-align: middle;" id="AttrTableTips">&#xe60b;</i>
                </div>
                <table id="AttrTable" lay-filter="AttrTable"></table>
            </div>
            <div class="layui-tab-item">
                <div style="margin-left: 10px">联动从表控件使其属性该表(可见)</div>
                <table id="DtlTable" lay-filter="DtlTable"></table>
            </div>
            <div class="layui-tab-item">
                <div style="margin-left: 10px">联动附件控件使其属性该表(可见)</div>
                <table id="AthTable" lay-filter="AthTable"></table>
            </div>
            <div class="layui-tab-item">
                <div style="margin-left:10px">
                    高级设置
                    <i class="layui-icon" style="vertical-align: middle;" id="SettingTips">&#xe60b;</i>
                </div>
                <div style="margin:10px 20px">
                    <div>JS脚本</div>
                    <textarea id="TB_Script" placeholder="请输入" class="layui-textarea"></textarea>
                    <div>提示信息</div>
                    <textarea id="TB_Tip" name="" placeholder="请输入" class="layui-textarea"></textarea>
                </div>
            </div>
        </div>
    </div>
    <!--Tab---end-->
    <!--设置列---start-->
    <script type="text/html" id="radioFieldsCfg">
        <div style="text-align:center;">
            <input type="radio" lay-filter="radioFieldsCfg" value="0" name="{{"radio-" + d.KeyOfEn}}" title="不设置" {{d.fieldsCfg=='0'?'checked':''}}= />
            <input type="radio" lay-filter="radioFieldsCfg" value="1" name="{{"radio-" + d.KeyOfEn}}" title="可用" {{d.fieldsCfg=='1'?'checked':''}}= />
            <input type="radio" lay-filter="radioFieldsCfg" value="2" name="{{"radio-" + d.KeyOfEn}}" title="可见" {{d.fieldsCfg=='2'?'checked':''}}= />
            <input type="radio" lay-filter="radioFieldsCfg" value="3" name="{{"radio-" + d.KeyOfEn}}" title="不可见" {{d.fieldsCfg=='3'?'checked':''}}= />
            <input type="radio" lay-filter="radioFieldsCfg" value="4" name="{{"radio-" + d.KeyOfEn}}" title="可用且必填" {{d.fieldsCfg=='4'?'checked':''}}= />
        </div>
    </script>
    <!--设置列---end-->
    <!--设置值列---start-->
    <script type="text/html" id="setValue">
        {{# if ((d.MyDataType == 2 && d.LGType == 1)||(d.UIContralType == 2 && d.MyDataType == 1)) {}}
        {{# var ses = new Entities("BP.Sys.SysEnums");}}
        {{# ses.Retrieve("EnumKey", d.UIBindKey);}}
        <div id="{{"DIV_" + d.KeyOfEn}}">
            <select class='form-control' name="{{"DDL-" + d.KeyOfEn}}" id="{{"DDL-" + d.KeyOfEn}}" lay-filter="setValue">
                <option value="" {{d.setVal == "" ? "selected" : ""}}=>请选择</option>
                {{# layui.each(ses, function(index, i){ }}
                <option value="{{i.IntKey}}" {{d.setVal == i.IntKey.toString() ? "selected" : ""}}=> {{i.Lab}} </option>
                {{# }); }}
            </select>
        </div>
        {{# } else if (d.LGType == "0" && d.MyDataType == "1" && d.UIContralType == 1) { }}<!--外键下拉-->
        {{# var sfTable = new Entity("BP.Sys.SFTable", d.UIBindKey);}}
        {{# var ens = sfTable.DoMethodReturnJSON("GenerDataOfJson");}}

        <div id="{{"DIV_" + d.KeyOfEn}}">
            <select class='form-control' name="{{"DDL-" + d.KeyOfEn}}" id="{{"DDL-" + d.KeyOfEn}}" lay-filter="setValue">
                <option value="" {{d.setVal == "" ? "selected" : ""}}=>请选择</option>
                {{# layui.each(ens, function(index, i){ }}
                <option value="{{i.No}}" {{d.setVal == i.No.toString() ? "selected" : ""}}=> {{i.Name}} </option>
                {{# }); }}
            </select>
        </div>
        {{# } else if (d.MyDataType==7) { }}
        <div class="layui-input-inline">
            <input type="text" id="DateTime" name="{{"DT_" + d.KeyOfEn }}" value="{{d.setVal}}" />
        </div>
        {{# } else if (d.MyDataType==6) {}}
        <input type="text" id="Date" name="{{"Date_" + d.KeyOfEn }}" value="{{d.setVal}}" />
        {{# } else { }}
        <input type="text" id="{{"TB_" + d.KeyOfEn }}" value="{{d.setVal}}" name="{{"TB_" + d.KeyOfEn }}" />
        {{# } }}
    </script>
    <!--设置值列---end-->
</body>
</html>
